// 对话引擎系统

use std::collections::HashMap;
use crate::symbol_table::SymbolTable;
use crate::causal_graph::CausalFragmentGraph;
use crate::knowledge_graph::KnowledgeGraph;
use crate::memory_system::MemorySystem;
use crate::types::{DialogueState, DialogueIntent, Intent, ResponseStrategy, DialogueAnalysis};
use crate::utils::{is_chinese_text, calculate_semantic_similarity};

// 对话引擎
#[derive(Debug)]
pub struct DialogueEngine {
    // 符号表
    pub symbol_table: SymbolTable,
    // 因果片段图
    pub causal_graph: CausalFragmentGraph,
    // 知识图谱
    pub knowledge_graph: KnowledgeGraph,
    // 记忆系统
    pub memory_system: MemorySystem,
    // 对话历史
    pub history: Vec<Vec<usize>>,
    // 当前对话状态
    pub current_state: DialogueState,
    // 当前对话意图
    pub current_intent: DialogueIntent,
    // 当前主题
    pub current_topics: Vec<usize>,
    // 对话轮次
    pub turn_count: usize,
}

impl DialogueEngine {
    pub fn new() -> Self {
        let mut engine = Self {
            symbol_table: SymbolTable::new(),
            causal_graph: CausalFragmentGraph::new(),
            knowledge_graph: KnowledgeGraph::new(),
            memory_system: MemorySystem::new(),
            history: Vec::new(),
            current_state: DialogueState::Initial,
            current_intent: DialogueIntent::Unknown,
            current_topics: Vec::new(),
            turn_count: 0,
        };
        
        // 初始化知识图谱
        engine.knowledge_graph.add_basic_entities(&mut engine.symbol_table);
        
        engine
    }
    
    // 检测对话状态
    pub fn detect_dialogue_state(&mut self, input: &[usize]) -> DialogueState {
        // 简单的状态检测逻辑
        if self.turn_count == 0 {
            DialogueState::Initial
        } else if self.detect_greeting_intent(input) {
            DialogueState::Greeting
        } else if self.detect_farewell_intent(input) {
            DialogueState::Farewell
        } else if self.detect_question_intent(input) {
            DialogueState::Questioning
        } else {
            DialogueState::InConversation
        }
    }
    
    // 检测对话意图
    pub fn detect_dialogue_intent(&mut self, input: &[usize]) -> DialogueIntent {
        if self.detect_greeting_intent(input) {
            DialogueIntent::Greeting
        } else if self.detect_farewell_intent(input) {
            DialogueIntent::Farewell
        } else if self.detect_question_intent(input) {
            DialogueIntent::Question
        } else if self.detect_information_intent(input) {
            DialogueIntent::Information
        } else if self.detect_opinion_intent(input) {
            DialogueIntent::Opinion
        } else if self.detect_command_intent(input) {
            DialogueIntent::Command
        } else {
            DialogueIntent::SmallTalk
        }
    }
    
    // 更新主题
    pub fn update_topics(&mut self, input: &[usize]) {
        // 提取输入中的关键词作为主题
        let mut word_frequency = HashMap::new();
        
        for &word_id in input {
            *word_frequency.entry(word_id).or_insert(0) += 1;
        }
        
        // 按频率排序
        let mut words: Vec<_> = word_frequency.into_iter().collect();
        words.sort_by(|a, b| b.1.cmp(&a.1));
        
        // 取前5个词作为主题
        self.current_topics = words.into_iter().take(5).map(|(id, _)| id).collect();
    }
    
    // 生成回应策略
    pub fn generate_response_strategy(&self, state: DialogueState, intent: DialogueIntent, is_chinese: bool) -> ResponseStrategy {
        match (state, intent, is_chinese) {
            (DialogueState::Greeting, _, true) => ResponseStrategy::GreetingChinese,
            (DialogueState::Greeting, _, false) => ResponseStrategy::Greeting,
            (DialogueState::Farewell, _, true) => ResponseStrategy::FarewellChinese,
            (DialogueState::Farewell, _, false) => ResponseStrategy::Farewell,
            (DialogueState::Questioning, _, true) => ResponseStrategy::AnswerChinese,
            (DialogueState::Questioning, _, false) => ResponseStrategy::Answer,
            (DialogueState::InConversation, DialogueIntent::Opinion, true) => ResponseStrategy::OpinionChinese,
            (DialogueState::InConversation, DialogueIntent::Opinion, false) => ResponseStrategy::Opinion,
            (DialogueState::InConversation, DialogueIntent::Command, _) => ResponseStrategy::Action,
            (_, _, true) => ResponseStrategy::GeneralChinese,
            (_, _, false) => ResponseStrategy::General,
        }
    }
    
    // 将符号转换为文本
    pub fn symbols_to_text(&self, symbols: &[usize]) -> String {
        self.symbol_table.symbols_to_text(symbols)
    }
    
    // 处理用户输入并生成回应
    pub fn respond(&mut self, input: &str) -> String {
        // 更新时间
        self.symbol_table.update_time();
        self.causal_graph.current_time += 1;
        self.knowledge_graph.update_time();
        self.memory_system.update_time();
        
        // 将输入转换为符号序列
        let input_syms = self.symbol_table.text_to_symbols(input);
        
        // 检测对话状态和意图
        self.current_state = self.detect_dialogue_state(&input_syms);
        self.current_intent = self.detect_dialogue_intent(&input_syms);
        
        // 更新主题
        self.update_topics(&input_syms);
        
        // 应用时间衰减
        self.symbol_table.apply_time_decay(0.99);
        self.causal_graph.apply_time_decay(0.99);
        self.memory_system.apply_time_decay(0.99);
        
        // 生成回应策略
        let is_chinese = is_chinese_text(input);
        let strategy = self.generate_response_strategy(self.current_state.clone(), self.current_intent.clone(), is_chinese);
        
        // 生成回应
        let response_syms = self.generate_response(&input_syms, &strategy);
        
        // 将符号转换为文本
        let response_text = self.symbols_to_text(&response_syms);
        
        // 添加到对话历史
        self.history.push(input_syms.clone());
        
        // 添加交互片段到因果图
        let mut interaction = input_syms.clone();
        interaction.extend(response_syms.clone());
        self.causal_graph.add_fragment(interaction.clone());
        
        // 更新符号关系
        self.update_symbol_relations(&interaction);
        
        // 添加到记忆系统
        let tags = vec![
            format!("state:{:?}", self.current_state),
            format!("intent:{:?}", self.current_intent),
        ];
        self.memory_system.add_short_term(interaction, tags);
        
        // 从对话中学习
        self.knowledge_graph.learn_from_dialogue(input, &response_text, &mut self.symbol_table);
        
        // 更新对话轮次
        self.turn_count += 1;
        
        // 定期整理记忆系统
        if self.turn_count % 10 == 0 {
            self.memory_system.organize_medium_term();
        }
        
        response_text
    }
    
    // 生成回应
    fn generate_response(&mut self, input_syms: &[usize], strategy: &ResponseStrategy) -> Vec<usize> {
        match strategy {
            ResponseStrategy::Greeting => self.generate_contextual_greeting(input_syms),
            ResponseStrategy::GreetingChinese => self.generate_contextual_greeting_chinese(input_syms),
            ResponseStrategy::Farewell => self.generate_contextual_farewell(input_syms),
            ResponseStrategy::FarewellChinese => self.generate_contextual_farewell_chinese(input_syms),
            ResponseStrategy::Answer => self.generate_intelligent_answer(input_syms),
            ResponseStrategy::AnswerChinese => self.generate_intelligent_answer_chinese(input_syms),
            ResponseStrategy::Action => self.generate_action_response(input_syms),
            ResponseStrategy::Opinion => self.generate_intelligent_opinion(input_syms),
            ResponseStrategy::OpinionChinese => self.generate_intelligent_opinion_chinese(input_syms),
            ResponseStrategy::General => self.generate_intelligent_response(input_syms),
            ResponseStrategy::GeneralChinese => self.generate_intelligent_response_chinese(input_syms),
        }
    }
    
    // 使用知识图谱生成智能回答
    fn generate_intelligent_answer_with_knowledge(&mut self, input_syms: &[usize]) -> Vec<usize> {
        // 将输入转换为文本
        let input_text = self.symbols_to_text(input_syms);
        
        // 查询知识图谱
        if let Some(answer) = self.knowledge_graph.query(&input_text, &self.symbol_table) {
            // 将答案转换为符号序列
            return self.symbol_table.text_to_symbols(&answer);
        }
        
        // 如果知识图谱中没有答案，尝试从记忆中搜索
        let relevant_memories = self.memory_system.search_relevant_memories(input_syms, &self.symbol_table, 3);
        
        if !relevant_memories.is_empty() {
            // 使用最相关的记忆生成回应
            let memory = &relevant_memories[0];
            
            // 找到记忆中与输入最不重叠的部分作为回应
            let mut response_syms = Vec::new();
            
            // 简单实现：返回记忆的后半部分
            if memory.content.len() > input_syms.len() {
                response_syms = memory.content[input_syms.len()..].to_vec();
            } else if !memory.content.is_empty() {
                response_syms = memory.content.clone();
            }
            
            if !response_syms.is_empty() {
                return response_syms;
            }
        }
        
        // 如果没有找到相关知识，使用智能回答生成
        self.generate_intelligent_answer(input_syms)
    }
    
    // 使用知识图谱生成中文智能回答
    fn generate_intelligent_answer_chinese_with_knowledge(&mut self, input_syms: &[usize]) -> Vec<usize> {
        // 将输入转换为文本
        let input_text = self.symbols_to_text(input_syms);
        
        // 查询知识图谱
        if let Some(answer) = self.knowledge_graph.query(&input_text, &self.symbol_table) {
            // 将答案转换为符号序列
            return self.symbol_table.text_to_symbols(&answer);
        }
        
        // 如果知识图谱中没有答案，尝试从记忆中搜索
        let relevant_memories = self.memory_system.search_relevant_memories(input_syms, &self.symbol_table, 3);
        
        if !relevant_memories.is_empty() {
            // 使用最相关的记忆生成回应
            let memory = &relevant_memories[0];
            
            // 找到记忆中与输入最不重叠的部分作为回应
            let mut response_syms = Vec::new();
            
            // 简单实现：返回记忆的后半部分
            if memory.content.len() > input_syms.len() {
                response_syms = memory.content[input_syms.len()..].to_vec();
            } else if !memory.content.is_empty() {
                response_syms = memory.content.clone();
            }
            
            if !response_syms.is_empty() {
                return response_syms;
            }
        }
        
        // 如果没有找到相关知识，使用中文智能回答生成
        self.generate_intelligent_answer_chinese(input_syms)
    }
    
    // 分析对话状态
    fn analyze_dialogue_state(&mut self, input_syms: &[usize]) -> DialogueAnalysis {
        // 计算对话轮次
        let turn_count = self.turn_count;
        
        // 分析意图
        let intent = self.detect_user_intent(input_syms);
        
        // 分析情感倾向
        let sentiment = self.analyze_sentiment(input_syms);
        
        // 计算连贯性
        let coherence = if !self.history.is_empty() {
            let last_input = &self.history[self.history.len() - 1];  
            self.calculate_coherence(input_syms, last_input)
        } else {
            0.5 // 初始对话的默认连贯性
        };
        
        // 更新主题
        self.update_topics(input_syms);
        let current_topics = self.current_topics.clone();
        
        // 生成摘要
        let summary = self.generate_summary(input_syms);
        
        DialogueAnalysis {
            turn_count,
            current_topics,
            sentiment,
            intent,
            coherence,
            summary,
        }
    }
    
    // 检测用户意图
    fn detect_user_intent(&self, input_syms: &[usize]) -> Intent {
        if self.detect_greeting_intent(input_syms) {
            Intent::Greeting
        } else if self.detect_farewell_intent(input_syms) {
            Intent::Farewell
        } else if self.detect_question_intent(input_syms) {
            Intent::Question
        } else if self.detect_action_request_intent(input_syms) {
            Intent::ActionRequest
        } else if self.detect_opinion_intent(input_syms) {
            Intent::Opinion
        } else if self.detect_information_providing_intent(input_syms) {
            Intent::Information
        } else {
            Intent::SmallTalk
        }
    }
    
    // 检测问候意图
    fn detect_greeting_intent(&self, input_syms: &[usize]) -> bool {
        let greeting_words = ["你好", "hello", "hi", "嗨", "您好"];
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if greeting_words.contains(&text.to_lowercase().as_str()) {
                    return true;
                }
            }
        }
        
        false
    }
    
    // 检测告别意图
    fn detect_farewell_intent(&self, input_syms: &[usize]) -> bool {
        let farewell_words = ["再见", "bye", "goodbye", "拜拜", "下次见"];
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if farewell_words.contains(&text.to_lowercase().as_str()) {
                    return true;
                }
            }
        }
        
        false
    }
    
    // 检测问题意图
    fn detect_question_intent(&self, input_syms: &[usize]) -> bool {
        for &sym_id in input_syms {
            if let Some(symbol) = self.symbol_table.get_symbol(sym_id) {
                if symbol.symbol_type == crate::symbol_table::SymbolType::Punctuation {
                    if let Some(text) = self.symbol_table.get_text(sym_id) {
                        if text == "?" || text == "？" {
                            return true;
                        }
                    }
                }
            }
        }
        
        // 检查疑问词
        let question_words = ["什么", "为什么", "怎么", "哪里", "谁", "what", "why", "how", "where", "who"];
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if question_words.contains(&text.to_lowercase().as_str()) {
                    return true;
                }
            }
        }
        
        false
    }
    
    // 检测行动请求意图
    fn detect_action_request_intent(&self, input_syms: &[usize]) -> bool {
        let action_words = ["请", "帮", "可以", "能否", "please", "help", "can", "could"];
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if action_words.contains(&text.to_lowercase().as_str()) {
                    return true;
                }
            }
        }
        
        false
    }
    
    // 检测观点意图
    fn detect_opinion_intent(&self, input_syms: &[usize]) -> bool {
        let opinion_words = ["认为", "觉得", "想", "看法", "观点", "think", "believe", "opinion"];
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if opinion_words.contains(&text.to_lowercase().as_str()) {
                    return true;
                }
            }
        }
        
        false
    }
    
    // 检测信息提供意图
    fn detect_information_providing_intent(&self, input_syms: &[usize]) -> bool {
        // 简单实现：如果句子较长且不包含疑问词，则认为是提供信息
        if input_syms.len() > 5 && !self.detect_question_intent(input_syms) {
            return true;
        }
        
        false
    }
    
    // 检测信息意图
    fn detect_information_intent(&self, input_syms: &[usize]) -> bool {
        // 简单实现：如果句子较长且不包含疑问词，则认为是提供信息
        if input_syms.len() > 5 && !self.detect_question_intent(input_syms) {
            return true;
        }
        
        false
    }
    
    // 检测命令意图
    fn detect_command_intent(&self, input_syms: &[usize]) -> bool {
        let command_words = ["告诉", "解释", "说明", "show", "tell", "explain"];
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if command_words.contains(&text.to_lowercase().as_str()) {
                    return true;
                }
            }
        }
        
        false
    }
    
    // 分析情感倾向
    fn analyze_sentiment(&self, input_syms: &[usize]) -> f32 {
        let positive_words = ["好", "棒", "喜欢", "开心", "高兴", "good", "great", "like", "happy", "love"];
        let negative_words = ["坏", "差", "讨厌", "难过", "生气", "bad", "terrible", "hate", "sad", "angry"];
        
        let mut positive_count = 0;
        let mut negative_count = 0;
        
        for &sym_id in input_syms {
            if let Some(text) = self.symbol_table.get_text(sym_id) {
                if positive_words.contains(&text.to_lowercase().as_str()) {
                    positive_count += 1;
                } else if negative_words.contains(&text.to_lowercase().as_str()) {
                    negative_count += 1;
                }
            }
        }
        
        if positive_count + negative_count == 0 {
            0.0 // 中性
        } else {
            (positive_count as f32 - negative_count as f32) / (positive_count + negative_count) as f32
        }
    }
    
    // 计算连贯性
    fn calculate_coherence(&self, input_syms: &[usize], previous_syms: &[usize]) -> f32 {
        if input_syms.is_empty() || previous_syms.is_empty() {
            return 0.0;
        }
        
        // 简化连贯性计算，避免复杂的语义相似度计算
        let mut common_symbols = 0;
        for &sym1 in input_syms {
            for &sym2 in previous_syms {
                if sym1 == sym2 {
                    common_symbols += 1;
                    break;
                }
            }
        }
        
        common_symbols as f32 / input_syms.len().max(previous_syms.len()) as f32
    }
    
    // 生成摘要
    fn generate_summary(&self, input_syms: &[usize]) -> Vec<usize> {
        // 简单实现：提取前几个关键词作为摘要
        let mut summary = Vec::new();
        
        for &sym_id in input_syms.iter().take(3) {
            if let Some(symbol) = self.symbol_table.get_symbol(sym_id) {
                if symbol.symbol_type != crate::symbol_table::SymbolType::Punctuation {
                    summary.push(sym_id);
                }
            }
        }
        
        summary
    }
    
    // 生成个性化问候回应
    fn generate_contextual_greeting(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        let greeting_text = match self.turn_count {
            0 => "Hello! Nice to meet you. How can I help you today?",
            1..=3 => "Hello again! How are you doing?",
            _ => "Hi! Good to see you again. What's on your mind?",
        };
        
        self.symbol_table.text_to_symbols(greeting_text)
    }
    
    // 生成中文个性化问候回应
    fn generate_contextual_greeting_chinese(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        let greeting_text = match self.turn_count {
            0 => "你好！很高兴认识你。今天我能帮你什么？",
            1..=3 => "你好！最近怎么样？",
            _ => "嗨！很高兴再次见到你。有什么想聊的吗？",
        };
        
        self.symbol_table.text_to_symbols(greeting_text)
    }
    
    // 生成告别回应
    fn generate_contextual_farewell(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        let farewell_text = match self.turn_count {
            0..=2 => "Goodbye! It was nice talking to you.",
            3..=5 => "Goodbye! Take care and have a great day!",
            _ => "Farewell! It was a pleasure talking with you. See you next time!",
        };
        
        self.symbol_table.text_to_symbols(farewell_text)
    }
    
    // 生成中文告别回应
    fn generate_contextual_farewell_chinese(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        let farewell_text = match self.turn_count {
            0..=2 => "再见！很高兴和你聊天。",
            3..=5 => "再见！保重，祝你有美好的一天！",
            _ => "告别！很荣幸与你交谈。下次见！",
        };
        
        self.symbol_table.text_to_symbols(farewell_text)
    }
    
    // 生成动作回应
    fn generate_action_response(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 简单实现：确认收到请求并表示会尽力帮助
        let response_text = "I understand your request. I'll do my best to help you with that.";
        self.symbol_table.text_to_symbols(response_text)
    }
    
    // 生成智能回答
    fn generate_intelligent_answer(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 优先使用知识图谱回答
        self.generate_intelligent_answer_with_knowledge(&[])
    }
    
    // 生成智能回答（中文）
    fn generate_intelligent_answer_chinese(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 优先使用知识图谱回答
        self.generate_intelligent_answer_chinese_with_knowledge(&[])
    }
    
    // 生成智能观点
    fn generate_intelligent_opinion(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 分析对话状态
        let analysis = self.analyze_dialogue_state(&[]);
        
        // 基于情感倾向和连贯性生成回应
        let response_text = if analysis.sentiment > 0.2 {
            "I understand your perspective. That's an interesting point of view."
        } else if analysis.sentiment < -0.2 {
            "I can see this is important to you. Let me think about what you've shared."
        } else {
            "Thank you for sharing your thoughts. That gives me something to consider."
        };
        
        self.symbol_table.text_to_symbols(response_text)
    }
    
    // 生成智能观点（中文）
    fn generate_intelligent_opinion_chinese(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 分析对话状态
        let analysis = self.analyze_dialogue_state(&[]);
        
        // 基于情感倾向和连贯性生成回应
        let response_text = if analysis.sentiment > 0.2 {
            "我理解你的观点。这是一个有趣的看法。"
        } else if analysis.sentiment < -0.2 {
            "我看得出这对你很重要。让我思考一下你分享的内容。"
        } else {
            "感谢分享你的想法。这给了我一些思考的空间。"
        };
        
        self.symbol_table.text_to_symbols(response_text)
    }
    
    // 生成智能回应
    fn generate_intelligent_response(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 尝试基于上下文预测回应
        if !self.history.is_empty() {
            let context = self.history.last().unwrap();
            
            // 尝试找到匹配的片段
            let matching_frags = self.causal_graph.get_matching_fragments(context, 2);
            
            if !matching_frags.is_empty() {
                // 选择最长的匹配片段
                if let Some(best_frag) = matching_frags.iter().max_by_key(|f| f.len()) {
                    // 取片段中上下文之后的部分作为回应
                    let context_len = context.len().min(best_frag.len());
                    if best_frag.len() > context_len {
                        return best_frag[context_len..].to_vec();
                    }
                }
            } else {
                // 尝试基于最后符号预测
                if let Some(&last) = context.last() {
                    if let Some(next) = self.causal_graph.predict_next(last, context, &self.symbol_table) {
                        let mut response = vec![next];
                        
                        // 继续预测，直到遇到标点或达到一定长度
                        let mut current = next;
                        let mut length = 1;
                        let mut visited_symbols = std::collections::HashSet::new(); // 防止循环
                        visited_symbols.insert(current);
                        
                        while length < 10 {
                            if let Some(next_sym) = self.causal_graph.predict_next(current, &[], &self.symbol_table) {
                                // 检查是否是标点符号
                                if let Some(symbol) = self.symbol_table.get_symbol(next_sym) {
                                    if symbol.symbol_type == crate::symbol_table::SymbolType::Punctuation {
                                        response.push(next_sym);
                                        break;
                                    }
                                }
                                
                                // 防止循环
                                if visited_symbols.contains(&next_sym) {
                                    break;
                                }
                                visited_symbols.insert(next_sym);
                                
                                response.push(next_sym);
                                current = next_sym;
                                length += 1;
                            } else {
                                break;
                            }
                        }
                        
                        return response;
                    }
                }
            }
        }
        
        // 如果没有生成回应，使用默认回应
        let default_text = "I understand. Please tell me more.";
        self.symbol_table.text_to_symbols(default_text)
    }
    
    // 生成智能回应（中文）
    fn generate_intelligent_response_chinese(&mut self, _input_syms: &[usize]) -> Vec<usize> {
        // 尝试基于上下文预测回应
        if !self.history.is_empty() {
            let context = self.history.last().unwrap();
            
            // 尝试找到匹配的片段
            let matching_frags = self.causal_graph.get_matching_fragments(context, 2);
            
            if !matching_frags.is_empty() {
                // 选择最长的匹配片段
                if let Some(best_frag) = matching_frags.iter().max_by_key(|f| f.len()) {
                    // 取片段中上下文之后的部分作为回应
                    let context_len = context.len().min(best_frag.len());
                    if best_frag.len() > context_len {
                        return best_frag[context_len..].to_vec();
                    }
                }
            } else {
                // 尝试基于最后符号预测
                if let Some(&last) = context.last() {
                    if let Some(next) = self.causal_graph.predict_next(last, context, &self.symbol_table) {
                        let mut response = vec![next];
                        
                        // 继续预测，直到遇到标点或达到一定长度
                        let mut current = next;
                        let mut length = 1;
                        while length < 10 {
                            if let Some(next_sym) = self.causal_graph.predict_next(current, &[], &self.symbol_table) {
                                // 检查是否是标点符号
                                if let Some(symbol) = self.symbol_table.get_symbol(next_sym) {
                                    if symbol.symbol_type == crate::symbol_table::SymbolType::Punctuation {
                                        response.push(next_sym);
                                        break;
                                    }
                                }
                                
                                response.push(next_sym);
                                current = next_sym;
                                length += 1;
                            } else {
                                break;
                            }
                        }
                        
                        return response;
                    }
                }
            }
        }
        
        // 如果没有生成回应，使用默认中文回应
        let default_text = "我理解。请告诉我更多。";
        self.symbol_table.text_to_symbols(default_text)
    }
    
    // 更新符号关系
    fn update_symbol_relations(&mut self, fragment: &[usize]) {
        // 更新符号之间的共现关系
        for i in 0..fragment.len() {
            for j in i + 1..fragment.len() {
                let id1 = fragment[i];
                let id2 = fragment[j];
                
                // 计算关系强度（基于距离）
                let distance = (j - i) as f32;
                let strength = 1.0 / distance;
                
                // 更新符号表中的关系
                self.symbol_table.update_symbol_relation(id1, id2, strength);
                self.symbol_table.update_symbol_relation(id2, id1, strength);
            }
        }
    }
    
    // 生成回答式中文回应
    fn generate_answer_chinese_response(&mut self, input_syms: &[usize]) -> Vec<usize> {
        // 尝试从知识图谱中获取答案
        self.generate_intelligent_answer_chinese_with_knowledge(input_syms)
    }
    
    // 生成观点式中文回应
    fn generate_opinion_chinese_response(&mut self, input_syms: &[usize]) -> Vec<usize> {
        self.generate_intelligent_opinion_chinese(input_syms)
    }
    
    // 生成一般中文回应
    fn generate_general_chinese_response(&mut self, input_syms: &[usize], context: &[usize]) -> Vec<usize> {
        let mut response_syms = Vec::new();
        
        // 尝试基于上下文预测回应
        if !context.is_empty() {
            // 尝试找到匹配的片段
            let matching_frags = self.causal_graph.get_matching_fragments(context, 2);
            
            if !matching_frags.is_empty() {
                // 选择最长的匹配片段
                if let Some(best_frag) = matching_frags.iter().max_by_key(|f| f.len()) {
                    // 取片段中上下文之后的部分作为回应
                    let context_len = context.len().min(best_frag.len());
                    if best_frag.len() > context_len {
                        response_syms = best_frag[context_len..].to_vec();
                    }
                }
            } else {
                // 尝试基于最后符号预测
                if let Some(&last) = context.last() {
                    if let Some(next) = self.causal_graph.predict_next(last, context, &self.symbol_table) {
                        response_syms.push(next);
                        
                        // 继续预测，直到遇到标点或达到一定长度
                        let mut current = next;
                        let mut length = 1;
                        let mut visited_symbols = std::collections::HashSet::new(); // 防止循环
                        visited_symbols.insert(current);
                        
                        while length < 10 {
                            if let Some(next_sym) = self.causal_graph.predict_next(current, &[], &self.symbol_table) {
                                // 检查是否是标点符号
                                if let Some(symbol) = self.symbol_table.get_symbol(next_sym) {
                                    if matches!(symbol.symbol_type, crate::symbol_table::SymbolType::Punctuation) {
                                        response_syms.push(next_sym);
                                        break;
                                    }
                                }
                                
                                // 防止循环
                                if visited_symbols.contains(&next_sym) {
                                    break;
                                }
                                visited_symbols.insert(next_sym);
                                
                                response_syms.push(next_sym);
                                current = next_sym;
                                length += 1;
                            } else {
                                break;
                            }
                        }
                    }
                }
            }
        }
        
        // 如果没有生成回应，使用默认中文回应
        if response_syms.is_empty() {
            let default_tokens = self.symbol_table.tokenize("我理解。请告诉我更多。");
            response_syms = default_tokens.into_iter()
                .map(|t| self.symbol_table.intern(&t))
                .collect();
        }
        
        response_syms
    }
}